package net.hserver.socket.server;

import net.hserver.socket.common.HSocketContext;
import net.hserver.socket.common.Handler;

import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class HSocketServer {

    private static final Logger LOGGER = Logger.getLogger(HSocketServer.class.getName());

    private AsynchronousServerSocketChannel ssc;

    private final CountDownLatch countDownLatch = new CountDownLatch(1);

    private final Integer port;

    private Handler handler;

    public HSocketServer(Integer port) {
        this.port = port;
    }

    public HSocketServer addHandler(Handler handler) {
        this.handler = handler;
        return this;
    }

    public void start() {
        try {
            AsynchronousChannelGroup cg = AsynchronousChannelGroup.withThreadPool(Executors.newFixedThreadPool(8));
            ssc = AsynchronousServerSocketChannel.open(cg);
            ssc.bind(new InetSocketAddress(port), 1000);
            //创建连接
            ssc.accept(this, new CompletionHandler<AsynchronousSocketChannel, HSocketServer>() {
                @Override
                public void completed(AsynchronousSocketChannel channel, HSocketServer attachment) {
                    try {
                        ssc.accept(attachment, this);
                    } finally {
                        new HSocketContext(channel,handler);
                    }
                }
                @Override
                public void failed(Throwable exc, HSocketServer attachment) {
                    ssc.accept(attachment, this);
                }
            });
            LOGGER.log(Level.INFO, "server port " + port);
            countDownLatch.await();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
